/* global window */
// http://github.com/zuiidea/antd-admin

import { stringify } from 'qs'
import { router, pathMatchRegexp } from 'utils'

import { queryUserInfo } from 'api';

const goDashboard = () => {
  if (pathMatchRegexp(['/', '/login'], window.location.pathname)) {
    router.push({
      pathname: '/',
    })
  }
}

export default {
  namespace: 'global',
  state: {
    routeList: [
      {
        id: '1',
        icon: 'laptop',
        name: 'Dashboard',
        zhName: '仪表盘',
        router: '/dashboard',
      },
    ],
    locationPathname: '',
    locationQuery: {},
  },
  //   监听路由事件
  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },
  },
  effects: {
    *query({ payload }, { call, put, select }) {
      // store isInit to prevent query trigger by refresh
    
    const isInit = JSON.parse(localStorage.getItem('isInit'))
      if (isInit === true) {
        goDashboard()
        return
      }
      // select，用于从state中获取数据
      const { locationPathname } = yield select(_ => _.global)
      // TODO: check user token
  //   const { isSuccess, user } = yield call(queryUserInfo, payload)
  //   if (isSuccess && user) {
  //     console.log('success')
  //   }elser{
        router.push({
          pathname: '/login',
          search: stringify({
            from: locationPathname,
          }),
        })
    // }
    },

    // *signOut({ payload }, { call, put }) {
    //   const data = yield call(logoutUser)
    //   if (data.success) {
    //     store.set('routeList', [])
    //     store.set('permissions', { visit: [] })
    //     store.set('user', {})
    //     store.set('isInit', false)
    //     yield put({ type: 'query' })
    //   } else {
    //     throw data
    //   }
    // },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  },
}
